package com.acme.bankclient;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	BankClient() {
	}

	void run() throws ClassNotFoundException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try {

            requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());

            while(true) {
                try {
                    System.out.println("Reguest: ");
                    String data = reader.readLine();
                    sendMessage(data);
                    if (data.equals("bye") || data.equals("close")) {
                        break;
                    } else {
                        receiveMessage();
                    }
                } catch (ClassNotFoundException e) {
                    System.err.println("Unknown format");
                }
            }
		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}


	void sendMessage(final String msg) throws IOException {
        out.writeObject(msg);
        out.flush();
        System.out.println("client>" + msg);
    }

    String receiveMessage() throws ClassNotFoundException, IOException {
        String reply = (String) in.readObject();
        System.out.println("answer> " + reply);
        return reply;
    }

	public static void main(final String args[]) throws ClassNotFoundException {
		BankClient client = new BankClient();
		client.run();
	}

}
